package com.qf.service.impl;

import com.qf.service.IndexService;
import com.qf.util.ConnectionUtil;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;

import java.io.IOException;
import java.util.Map;

/*
杨威
2022/1/17
21:07
*/

//创建库
public class IndexServiceImpl implements IndexService {
    public void createIndex(String index) throws IOException {
        //第一步获取连接
        RestHighLevelClient client = ConnectionUtil.getClient();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        //设置库的属性
        CreateIndexRequest settings = createIndexRequest.settings(
                Settings.builder()
                        .put("number_of_shards", 5)
                        .put("number_of_replicas", 1).build());

        //json有两种格式 object{}和array[]
        XContentBuilder mappings = JsonXContent.contentBuilder().startObject()
                .startObject("properties")
                .startObject("name").field("type", "text").field("analyzer", "ik_max_word")
                .endObject().startObject("count").field("type", "long").endObject()
                .startObject("on-sale").field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis").endObject()
                .startObject("descr").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .endObject().endObject();


        createIndexRequest.mapping("lala",mappings);//设置列的信息
        CreateIndexResponse response = client.indices()//和库相关的操作都在这里
                .create(createIndexRequest, RequestOptions.DEFAULT);


        System.out.println("resp = " + response);
    }

    public void createIndex(CreateIndexRequest request) throws IOException {

    }
}
